package com.wans.guli.gateway.filter;

import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
public class LoggingFilter implements GlobalFilter, Ordered {

    private static final Logger log = LoggerFactory.getLogger(LoggingFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        // 记录请求信息
        logRequest(request);

        // 包装响应以捕获响应数据
        ServerHttpResponse originalResponse = exchange.getResponse();
        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                        DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
                        DataBuffer join = factory.join(dataBuffers);
                        byte[] content = new byte[join.readableByteCount()];
                        join.read(content);

                        // 释放缓冲区
                        DataBufferUtils.release(join);

                        // 重新包装数据
                        String responseBody = new String(content, StandardCharsets.UTF_8);

                        // 记录响应信息
                        logResponse(exchange, responseBody);

                        return bufferFactory.wrap(content);
                    }));
                }
                return super.writeWith(body);
            }
        };

        // 替换响应对象并继续执行过滤器链
        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }

    private void logRequest(ServerHttpRequest request) {
        StringBuilder logMessage = new StringBuilder("\n\t\t\t\t\t\t\t\t=============== Gateway 请求 ===============\n");
        logMessage.append("路径: ").append(request.getURI()).append("\n");
        logMessage.append("请求方法: ").append(request.getMethod()).append("\n");

        // 记录请求头
        logMessage.append("请求头:\n");
        HttpHeaders headers = request.getHeaders();
        for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
            logMessage.append("  ").append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
        }

        // 记录查询参数
        logMessage.append("请求参数:\n");
        request.getQueryParams().forEach((name, values) ->
                logMessage.append("  ").append(name).append(": ").append(values).append("\n"));

        log.info(logMessage.toString());
    }

    private void logResponse(ServerWebExchange exchange, String responseBody) {
        ServerHttpResponse response = exchange.getResponse();
        StringBuilder logMessage = new StringBuilder("\n\t\t\t\t\t\t\t\t=============== Gateway 响应 ===============\n");
        logMessage.append("响应状态: ").append(response.getStatusCode()).append("\n");

        // 记录响应头
        logMessage.append("响应头:\n");
        response.getHeaders().forEach((name, values) ->
                logMessage.append("  ").append(name).append(": ").append(values).append("\n"));

        // 记录响应体
        logMessage.append("响应体:\n");
        //logMessage.append(responseBody).append("\n");

        log.info(logMessage.toString());
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE; // 最高优先级
    }
}
